/* Written By : Chang Hyun Park
 * Student ID : 2007002320
 * Subject	  : Data Communication
 * File Name  : Receive.java
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;


public class Receive extends Thread
{
	private DatagramSocket clientSocket;
	private DatagramPacket recvPacket;
//	private DatagramPacket sendAck;
//	private InetAddress remoteAddress;
//	private int remotePort;
//	private int ackCount;
	private byte[] recvbuff;
//	private byte[] ackbuff;
	private Send sendThread;
	
	
	public Receive(DatagramSocket clientSocket, Send sendThread) throws Exception
	{
		this.clientSocket = clientSocket;
		this.sendThread = sendThread;
//		ackbuff = new byte[4];//Size of int
	}
	
	public void run()
	{
		while(true)
		{
			try
			{
				//Receive
				recvbuff = new byte[1024];
				recvPacket = new DatagramPacket(recvbuff,recvbuff.length);
				clientSocket.receive(recvPacket);
				sendThread.resume();//Resumes the Send thread after Receiving data!
				String temprecv = new String(recvPacket.getData());
//				System.out.println("Error Checking... \""+temprecv+"\"");
				
				//Send Ack
				/*String tempAck = new String(recvPacket.getData());
				ackCount = Integer.parseInt(tempAck.substring(0, 2));
				sendAck = new DatagramPacket(ackbuff, ackbuff.length, recvPacket.getAddress(), recvPacket.getPort());
				sendAck.setData(Integer.toString(ackCount).getBytes());
				clientSocket.send(sendAck);
				System.out.println("Sent Ack value of "+ackCount);*/
				
				//Analyze Received Packet and Print onto screen
//				String tempBuffer = new String(recvPacket.getData().toString()/*.substring(2)*/);//First 2 characters of the string will be 2-digit acks.
				String tempAddress = new String(recvPacket.getAddress().toString().substring(1));
				int tempPort = recvPacket.getPort();
				System.out.println("["+tempAddress+":"+tempPort+"] Says : "+temprecv);
				//this.suspend();//Wait until Send releases suspend!
			} catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
